package com.gopay.bis.service.bank.impl.wap;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.constants.BisPayConstants;
import com.gopay.bis.manager.bank.Wap.AbcWapB2cManager;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.AbcConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.abc.ebank.AbcB2cMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.WapPayInteractRemoteService;

/**
 * 农行wapB2C业务实现
 * @author wangxintao
 *
 */
public class AbcWapPayB2CBankServiceImpl implements WapPayInteractRemoteService {
	
    @Resource(name = "abcWapB2cManager")
    private AbcWapB2cManager abcWapB2cManager;

    /**
	 * 银行支付类请求
	 * 
	 * @param BaseMessage
	 * @return Result
	 */
	public Result pay(BaseMessage base) {
		Result result = new Result(false);
		try {
			AbcB2cMessage messageB2C = new AbcB2cMessage();
			BeanUtils.copyProperties(base, messageB2C);
			messageB2C = (AbcB2cMessage) abcWapB2cManager.sign(messageB2C);
			result.setDefaultModel(messageB2C);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6029);
		}
		return result;
	}

	/**
	 * 银行返回类请求
	 * 
	 * @param BaseMessage
	 * @return Result
	 */
	public Result bankBack(BaseMessage base) {
		Result result = new Result(false);
		try {
			AbcB2cMessage messageB2C = new AbcB2cMessage();
			BeanUtils.copyProperties(base, messageB2C);
			AbcB2cMessage b2c = (AbcB2cMessage) abcWapB2cManager.verify(messageB2C);
			b2c.setOrderId(b2c.getResOrderNo());
			b2c.setBankOrderId(b2c.getResOrderNo());
			b2c.setAmount(new BigDecimal(b2c.getResAmount()));
			result.setModel("res", b2c);
			result.setDefaultModel(b2c != null ? true : false);
			result.setSuccess(true);

			Map<String, String> param = new HashMap<String, String>();
			if((Boolean) result.getDefaultModel()){
				if (b2c.isSuccess()) {
					param.put("orderId", b2c.getResOrderNo());
					param.put("amt", b2c.getResAmount());
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "00");
					param.put("retCode", "00");
					param.put("retMsg", "验签成功");
					param.put("signData", messageB2C.getSignMessage());
					param.put("isFront", String.valueOf(base.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(true);
				} else {
					// 通知后台地址该订单失败
					param.put("orderId", b2c.getResOrderNo());
					param.put("amt", b2c.getResAmount());
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "01");
					param.put("retCode", "01");
					param.put("retMsg", "验签失败");
					param.put("signData", messageB2C.getSignMessage());
					param.put("isFront", String.valueOf(base.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(false);
				}
			}
		
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		return result;
	}

	/**
	 * 银行查询类请求
	 * 
	 * @param BaseMessage
	 * @return Result
	 */
	public Result query(BaseMessage base) {
		Result result = new Result(false);
		try {
			AbcB2cMessage messageB2C = new AbcB2cMessage();
			BeanUtils.copyProperties(base, messageB2C);
			AbcB2cMessage b2c = (AbcB2cMessage) abcWapB2cManager.query(messageB2C);
			result.setDefaultModel(b2c);
			result.setSuccess(true);
			if(BisPayCheckUtils.checkExternalOrderID(messageB2C.getOrderId())){
				Map<String, String> param = new HashMap<String, String>();
				param.put("orderId", messageB2C.getResOrderNo());
				param.put("amount", messageB2C.getResAmount());
				if (b2c == null) {
					// 查询订单为空
					param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
					param.put("returnMessage", "银行返回对账结果为空");
					param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
		        }else if (StringUtils.isEmpty(b2c.getOrderStatus())) {
		        	// 查询订单错误
					param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
					param.put("returnMessage", b2c.getErrorMessage());
					param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
				}else{
					param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
			        if(b2c.getOrderStatus() != null && !b2c.getOrderStatus().equals("")){
			         // 订单状态成功(订单已支付) 03状态银行已不用
//                      if (AbcConstants.ABC_B2C_ORDERSTATUS_PAYMENT_ORDERS.equals(b2c.getOrderStatus())) {
//                          param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
//                          param.put("returnMessage", AbcConstants.ABC_B2C_PAYMENT_ORDERS_MESSAGE);                    
//                      }
		     			// 订单状态成功(订单已结算)
		     			if (AbcConstants.ABC_ORDERSTATUS_SETTLEMENT_ORDER.equals(b2c.getOrderStatus())) {
							param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
							param.put("returnMessage", AbcConstants.ABC_SETTLEMENT_ORDER_MESSAGE);		
		     			}
		     			// 订单状态暂不处理(订单已建立，等待支付)
		     			else if (AbcConstants.ABC_ORDERSTATUS_ESTABLISH.equals(b2c.getOrderStatus())) {
							param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
							param.put("returnMessage", AbcConstants.ABC_ESTABLISH_MESSAGE);
		     			}
		     			// 订单状态暂不处理(订单无回应)
		     			else if (AbcConstants.ABC_ORDERSTATUS_CONSUMER_PAID.equals(b2c.getOrderStatus())) {
							param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
							param.put("returnMessage", AbcConstants.ABC_CONSUMER_PAID_MESSAGE);
		     			}
		     			// 订单状态暂不处理(订单已退款)
		     			else if (AbcConstants.ABC_ORDERSTATUS_REFUND.equals(b2c.getOrderStatus())) {
							param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
							param.put("returnMessage", AbcConstants.ABC_REFUND_MESSAGE);
		     			}
		     			// 订单状态失败处理(订单已取消)
		     			else if (AbcConstants.ABC_ORDERSTATUS_CANCEL.equals(b2c.getOrderStatus())) {
		     				//失败处理
							param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
							param.put("returnMessage", AbcConstants.ABC_CANCEL_MESSAGE);
		     			}
		     			// 订单状态失败处理(订单支付失败）
		     			else if (AbcConstants.ABC_ORDERSTATUS_FAILURE.equals(b2c.getOrderStatus())) {
							param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
							param.put("returnMessage", AbcConstants.ABC_FAILURE_MESSAGE);
		     			}else{
							param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
							param.put("returnMessage", "交易结果未明确");
		     			}
		            }else{
						param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
						param.put("returnMessage", "银行返回订单未查到");
		            }
				}
				result.setModel("queryResult", param);
			}			
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6033);
		}
		return result;
	}

	/**
	 * 银行退款类请求
	 * 
	 * @param BaseMessage
	 * @return Result
	 */
	@Override
	public Result refund(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 银行日终类请求
	 * 
	 * @param BaseMessage
	 * @return Result
	 */
	@Override
	public Result dayend(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result queryBack(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

   
}
